Vue.use(Vuex)
import Vue from 'vue'
import Vuex from 'vuex'
import {
	wxLoginApi
} from "@api";
//用户数据
const USER = {
	namespaced: true,
	state: () => ({
		userInfo: {}, //用户信息
		token: null, //用户的token
		agreement: false, //是否同意协议
	}),
	getters: {
		isLogin(state) {
			state.token =  uni.getStorageSync("token");
			if (state.token)
				return true
			return false
		}
	},
	mutations: {
		setToken(state, token) {
			state.token = token;
			uni.setStorageSync("token", token);
		},
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo;
			uni.setStorageSync("userInfo", userInfo);
		},
		setAgreement(state, agreement) {
			state.agreement = agreement;
			uni.setStorageSync("agreement", agreement);
		},
	},
	actions: {
		login({
			commit
		}, {
			userInfo,
			code
		}) {
			return new Promise((resolve, reject) => {
				wxLoginApi({
						code,
						...userInfo,
						userName: userInfo.nickName
					})
					.then(({
						token,
						user
					}) => {
						console.log("wxLoginApi:", token);				
						commit("setToken", token);
						commit("setUserInfo", user);
					})
					.catch((err) => reject(err));
			});
		},
		logout({
			commit
		}) {
			commit("setToken", "");
			commit("setUserInfo", {});
			//清空所有本地存储
			uni.clearStorageSync();
		},
		init({
			commit
		}) {
			commit("setAgreement", uni.getStorageSync("agreement") || false);
			commit("setUserInfo", uni.getStorageSync("userInfo") || {});
			commit("setToken", uni.getStorageSync("token") || "");
		},
	},
};


//非用户的其他全局逻辑数据
const DATA = {
	state: () => ({}),
	getters: {},
	mutations: {},
	actions: {}
}

const store = new Vuex.Store({
	modules: {
		USER,
		DATA
	}
})
export default store
